//类似Android CollapsingToolbar
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../generated/assets.dart';

class CollapsingToolbarPage extends StatefulWidget {
  const CollapsingToolbarPage({super.key});

  @override
  State<CollapsingToolbarPage> createState() => _CollapsingToolbarPageState();
}

class _CollapsingToolbarPageState extends State<CollapsingToolbarPage> {
  final ScrollController _scrollController = ScrollController();
  double _appBarAlpha = 0.0;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      final double offset = _scrollController.offset;
      _appBarAlpha = (offset / 100).clamp(0.0, 1.0);
      setState(() {});
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _buildCorrectLayout(), // 修复布局结构
    );
  }

  Widget _buildCorrectLayout() {
    return NestedScrollView(
      controller: _scrollController,
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [
          // 关键修复2：添加重叠吸收器
          SliverOverlapAbsorber(
            handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
            sliver: SliverAppBar(
              expandedHeight: 250,
              flexibleSpace: FlexibleSpaceBar(
                collapseMode: CollapseMode.pin,
                expandedTitleScale: 2.0,
                background: Image.asset(
                  Assets.imgTopImg,
                  fit: BoxFit.cover,
                ),
              ),
              floating: true,
              // 允许轻扫展开
              snap: true,
              // 快速吸附效果
              pinned: true,
              // 折叠时保留固定高度
              backgroundColor: Colors.white,
              leading: _buildLeadingIcon(),
              actions: _buildActionIcons(),
              title: _buildTitle(),
              surfaceTintColor: Colors.transparent,
              // 关键修复1：添加重叠处理
              forceElevated: innerBoxIsScrolled,
            ),
          ),
        ];
      },
      // 关键修复3：使用SliverList包裹内容
      body: Builder(
        builder: (context) {
          return CustomScrollView(
            // physics: const AlwaysScrollableScrollPhysics(), // 关键点 2：嵌套滚动启用
            // 关键修复4：添加重叠注入器
            slivers: [
              // 自动注入 SliverAppBar 的占位空间
              SliverOverlapInjector(
                handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
              ),
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) => ListTile(title: Text('Item $index')),
                  childCount: 100,
                ),
              ),
              // SliverFillRemaining(
              //   // 关键点 3：填充剩余空间
              //   hasScrollBody: false,
              //   child: Container(
              //     color: Colors.white,
              //     child: const Center(
              //       child: Text('底部填充区域，支持弹性滚动'),
              //     ),
              //   ),
              // ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildLeadingIcon() {
    return IconButton(
      icon: Icon(
        Icons.menu,
        color: _appBarAlpha > 0.5 ? Colors.black : Colors.white,
      ),
      onPressed: () {},
    );
  }

  List<Widget> _buildActionIcons() {
    return [
      IconButton(
        icon: Icon(Icons.search, color: _appBarAlpha > 0.5 ? Colors.black : Colors.white),
        onPressed: () {},
      ),
      IconButton(
        icon: Icon(Icons.share, color: _appBarAlpha > 0.5 ? Colors.black : Colors.white),
        onPressed: () {},
      ),
      IconButton(
        icon: Icon(Icons.more_vert, color: _appBarAlpha > 0.5 ? Colors.black : Colors.white),
        onPressed: () {},
      ),
    ];
  }

  Widget _buildTitle() {
    return Text(
      'Collapsing Toolbar',
      style: TextStyle(
        color: _appBarAlpha > 0.5 ? Colors.black : Colors.white,
        fontSize: 18,
      ),
    );
  }

  Widget _buildScrollContent() {
    return ListView.builder(
      padding: EdgeInsets.only(top: 0 // 留出顶部间距
          ),
      itemCount: 10,
      itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
    );
  }
// Widget _buildScrollContent() {
//   return Builder(
//     builder: (context) {
//       // 关键修复2：动态计算可用高度
//       final mediaQuery = MediaQuery.of(context);
//       return SizedBox(
//         // 减去状态栏和导航栏高度
//         height: mediaQuery.size.height - mediaQuery.padding.top - kToolbarHeight,
//         child: ListView.builder(
//           padding: EdgeInsets.only(
//               top: 8, // 留出顶部间距
//               bottom: mediaQuery.padding.bottom // 避免底部被遮挡
//           ),
//           itemCount: 10,
//           itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
//         ),
//       );
//     },
//   );
// }
}
